<!-- 目的地页面 -->
<template>
  <div class="destination-page">
    <nav-bar :activeComponent="activeComponent"></nav-bar>
    <!-- 图钉墙 -->
    <div class="pin-wall-container">
      <!-- 无限滚动图钉墙 -->
      <div class="pin-wall">
        <div class="pin-wall-track">
          <!-- 第一组图钉 -->
          <div class="pin" v-for="(location, index) in filteredLocations" :key="'a-'+index"    @click="goToSpotDetail(location.spotId)">
            <div class="pin-image">
<!--              <img :src="location.image" :alt="location.name" />-->
<!--              <img :src="'/api/images/'+location.image" :alt="location.name" />-->
              <img :src="'http://localhost:5173/api/images/' + location.coverImage">

              <div class="pin-overlay" @click.stop="toggleFavorite(location)">
                <i
                  :class="['fas', location.isFavorite ? 'fa-heart text-red' : 'fa-heart text-gray']">
                </i>
                <span>{{ location.isFavorite ? "已收藏" : "收藏" }}</span>
              </div>
            </div>
            <div class="pin-content">
              <h3>{{ location.spotName }}</h3>
              <p>  {{ location.city?.province?.provinceName || '未知省份' }} · {{ location?.city?.cityName }}</p>
            </div>
          </div>

          <!-- 复制一组图钉用于无缝滚动 ggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg-->

        </div>
      </div>
    </div>
    <el-dialog v-model="showModal" title="选择收藏夹" width="400px" :close-on-click-modal="false">
      <ul class="folder-list">
        <li v-for="folder in folders" :key="folder.folderId"
            @click="selectedFolderId = folder.folderId"
            :class="{ active: selectedFolderId === folder.folderId }">
          {{ folder.name }}
        </li>
      </ul>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showModal = false">取消</el-button>
          <el-button type="primary" @click="confirmFavorite" :disabled="!selectedFolderId">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 左右布局 -->
    <div class="content-layout">
      <!-- 左侧：河北城市热度排行榜 -->
      <div class="left-section">
        <h2><i class="fas fa-fire"></i> 河北省城市热度排行榜</h2>
        <ul class="hot-cities-list">
          <li v-for="(city, index) in hebeiCities" :key="index" class="rank-list-item" @click="goToCityDetail(city.code)">
            <span class="city-rank" :class="{ 'top-three': index < 3 }">{{ index + 1 }}</span>
            <span class="city-name">{{ city.cityName }}</span>
            <span class="city-trend">
              <i class="fas fa-arrow-up" v-if="city.trend==='up'"></i>
              <i class="fas fa-arrow-down" v-if="city.trend==='down'"></i>
              <i class="fas fa-minus" v-if="city.trend==='stable'"></i>
            </span>
          </li>
        </ul>
      </div>


      <div class="right-section">
        <h2><i class="fas fa-compass"></i> 探索主题旅行</h2>
        <div class="theme-grid">
          <div class="theme-card" v-for="(theme, index) in themes" :key="index" @click="navigateToTheme(theme.clazzId)">
            <div class="theme-image">
              <img :src="'http://localhost:5173/api/images/' + theme.image" :alt="theme.clazzName " />
<!--              <img :src="theme.imagePath" :alt="theme.clazzName " />-->
              <div class="theme-overlay">
                <span>探索{{ theme.clazzName }}之旅</span>
              </div>
            </div>
            <div class="theme-content">
              <h3>{{ theme.clazzName }}</h3>
              <p>{{ theme.description }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部 Footer -->
    <FooterComponent />

  </div>
</template>

<script>
  import { ref, computed, onMounted, defineExpose ,reactive} from 'vue';
  import NavBar from "@/components/NavBar.vue";
  import router from "@/router";
  import {getSpotClass, getTopSpot,getSpotShow ,checkFavoriteStatus, getHebeiCities} from "@/api/destinations.js";
  import {favouriteAdd,removeFavorite ,userAllFavourite} from "@/api/bookmark.js";
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { useStore } from 'vuex' //
  import FooterComponent from '@/components/common/FooterComponent.vue';
  export default {
    name: 'DestinationPage',
    components: { NavBar },
    
    setup() {
      // 响应式数据和计算属性
      const activeComponent = ref('destinations');
      const store = useStore();
      const locations = ref([ ]);
      const topCities = ref();
      const hebeiCities = ref([]); // 新增河北城市列表
      const showModal = ref(false); // 控制弹窗显示
      const selectedFolderId = ref(null); // 选中的收藏夹 ID

      // 修改获取河北省城市的函数
      const updateHebeiCities = () => {
        // 调用新的 API 获取河北省城市
        getHebeiCities(5).then((res) => {
          hebeiCities.value = res.data;
          console.log("获取河北省城市成功:", hebeiCities.value);
        }).catch((error) => {
          console.error("获取河北省城市失败:", error);
        });
      }
      
      // 导航到城市详情页面
      const goToCityDetail = (cityCode) => {
        router.push({
          name: 'CityDetail',  // 使用命名路由
          params: { regionId: cityCode }  // 通过 params 而非 query 传递参数
        });
      }
 
    // 虚拟收藏夹数据
    const folders = ref([
    ]);
    const data = {
        userId: store.state.userInfo?.userId,  // 获取用户 ID
        bindId: location.id,  // 景点 ID
        type: 4,
        folderId:-1
      };

    // 打开收藏夹弹窗

      const themes = ref([]);
      const toggleFavorite=(location)=> {

        console.log(`output->location`,location)
        data.bindId=location.spotId;
      if (location.isFavorite) {

        removeFavorite(data)
          .then((res) => {
            location.isFavorite = 0; // 更新 UI
            ElMessage.success(res.data || '您已经取消收藏！');
          })
          .catch((error) => {
            console.error("取消收藏失败:", error);
          });
      } else {
        // 添加收藏
        showModal.value = true;

      }
    }
   const confirmFavorite=()=>{

data.folderId=selectedFolderId.value;
console.log(`output->data`,data)
     favouriteAdd(data)
          .then((res) => {

            showModal.value = false;
            updateSpotShow();
            ElMessage.success(res.data || '收藏成功！');

          })
          .catch((error) => {
            console.error("添加收藏失败:", error);
          });
   }
      const updateTop=()=>{
        // 获取并更新 topCities 数组
        getTopSpot(10).then((res) => {
          topCities.value = res.data;

        });
      }
      const updateSpotClass=()=>{
        // 获取并更新 spotClass 数组
        getSpotClass().then((res) => {
          themes.value = res.data;

        });
      }
    const getallfavorites = () => {
    userAllFavourite({
      userId: store.state.userInfo?.userId,
      name: "",
      folderId: null,
    }).then(res => {
      if (res.state === 0 && res.data) {

        folders.value = res.data;

      }
    }).catch(error => {
      console.error("获取收藏数据失败:", error);
    });
  };

      const updateSpotShow = () => {
  // 获取并更新 spotShow 数组
  getSpotShow().then((res) => {
    locations.value = res.data;
    alert(res.data[0].coverImage)
    const spotIds = locations.value.map((spot) => spot.spotId);
    const userId = store.state.userInfo?.userId; // 获取用户 ID

    // 构造所有收藏状态的请求

    const favoritePromises = spotIds.map((spotId) => {
  const datat1 = {
    userId: userId,
    bindId: spotId,
    type: 4
  };
  return checkFavoriteStatus(datat1);
});

    // 并行发送请求，等待所有请求完成
    Promise.all(favoritePromises)
      .then((res) => {
        // 赋值收藏状态

        locations.value.forEach((spot, index) => {

          if(res[index].data>0)
         {
          spot.isFavorite = 1;
         }else{
          spot.isFavorite = 0;
         }
        });


      })
      .catch((error) => {
        console.error("Failed to update favorite status:", error);
      });
  }).catch((error) => {
    console.error("Failed to fetch spot show:", error);
  });
};

      onMounted(() => {
        updateHebeiCities(); 
        updateSpotClass();
        updateSpotShow();
        getallfavorites();
      });
      const searchQuery = ref('');
  
      const filteredLocations = computed(() => {
        if (!searchQuery.value) {
          return locations.value;
        }
        const query = searchQuery.value.toLowerCase();
        return locations.value.filter(
          (location) =>
            location.spotName.toLowerCase().includes(query) ||
            location.city?.province?.provinceName.toLowerCase().includes(query) ||
            location.city.cityName.toLowerCase().includes(query)
        );
      });
  
      const goToCityIntro = () => {
        router.push({ path: '/CityDetail' }); // 可以传递参数
      };
      const goToSpotDetail=(locationId)=> {
      router.push({
        path: '/spotsIntro',
        query: { id: locationId }
      });
    }
      const searchLocation = () => {
        console.log('搜索地点:', searchQuery.value);
      };
  
      onMounted(() => {
        console.log('DestinationPage component has been mounted');
      });
  
      // 暴露需要给父组件的值
      defineExpose({
        searchQuery,
        filteredLocations,
        goToCityIntro,
        searchLocation,

      });
      // 导航到主题页面
      const navigateToTheme = (themeId) => {
  router.push({
    path: '/themePage',
    query: { id: themeId }
  });
};


      return {
        activeComponent,
        locations,
        themes,
        searchQuery,
        filteredLocations,
        goToCityDetail, 
        searchLocation,
        updateHebeiCities, 
        updateSpotClass,
        updateSpotShow,
        toggleFavorite,
        showModal,folders,
        selectedFolderId,
        confirmFavorite,
        getallfavorites,
        navigateToTheme,
        goToSpotDetail,
        hebeiCities
      };
    },
  };
  </script>
  
<style scoped>
@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@300;400;500;700&display=swap');
@import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css');
/* 排行榜样式 */
.rank-list-item:hover{
  background-color: #dcdfe6;
}
.rank-list-item{
  width: 100%;
  padding:0 5px;
}

.destination-page {
  font-family: 'Noto Sans SC', sans-serif;
  background-color: #f9f9f9;
  color: #333;
}

/* 图钉墙容器 */
.pin-wall-container {
  position: relative;
  height: 58vh; /* 进一步增加容器高度 */
  margin-bottom: 0; /* 移除底部外边距 */
  padding: 5px 0 0 0; /* 只保留顶部内边距 */
  overflow: hidden;
  background: linear-gradient(135deg, #e8f4f8 0%, #d1e8f2 100%);
  border-bottom: 1px solid #d0e6f5;
  box-shadow: inset 0 -8px 15px rgba(0, 0, 0, 0.04);
}

/* 图钉墙样式 */
.pin-wall {
  height: 100%;
  width: 100%;
  overflow: hidden;
  position: relative;
}

.pin-wall-track {
  display: flex;
  position: absolute;
  top: 0;
  left: 0;
  animation: scrollPins 80s linear infinite;
  width: fit-content;
  padding: 10px 0; /* 减少轨道上下内边距 */
}
/* 当鼠标悬停在容器上时暂停动画 */
.pin-wall-container:hover .pin-wall-track {
  animation-play-state: paused;
}

/* 图钉样式 */
.pin {
  width: 280px;
  height: 38vh; /* 增加总体高度占比 */
  margin: 10px 15px; /* 减少上下margin */
  background-color: white;
  border-radius: 15px;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  transition: all 0.4s cubic-bezier(0.165, 0.84, 0.44, 1);
}

.pin:hover {
  transform: translateY(-12px) scale(1.02);
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.12);
}
.pin-image {
  height: 75%; /* 增加图片占卡片的高度比例 */
  overflow: hidden;
  position: relative;
  border-bottom: 1px solid #f5f5f5;
}



.pin-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.6s ease-out;
}

.pin:hover .pin-image img {
  transform: scale(1.08);
}
.pin-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(to top, rgba(0,0,0,0.7) 0%, rgba(0,0,0,0.2) 50%, rgba(0,0,0,0) 100%);
  opacity: 0;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  align-items: center;
  padding-bottom: 20px;
  color: white;
  transition: opacity 0.4s ease;
}

.pin-overlay i {
  font-size: 22px;
  margin-bottom: 8px;
  filter: drop-shadow(0 2px 3px rgba(0,0,0,0.3));
}
.pin:hover .pin-overlay {
  opacity: 1;
}

.pin-overlay span {
  font-weight: 500;
  letter-spacing: 0.5px;
  filter: drop-shadow(0 1px 2px rgba(0,0,0,0.5));
}

.pin-content {
  height: 25%; /* 相应减少内容区域高度 */
  padding: 12px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  background: white;
}
.pin-content h3 {
  margin: 0 0 6px 0;
  font-size: 17px;
  font-weight: 600;
  color: #2c3e50;
  line-height: 1.3;
}

.pin-content p {
  margin: 0;
  font-size: 14px;
  color: #7f8c8d;
  line-height: 1.4;
}
/* 图钉墙滚动动画 */
@keyframes scrollPins {
  0% {
    transform: translateX(0);
  }
  100% {
    transform: translateX(-50%);
  }
}

/* 左右布局样式 */
.content-layout {
  display: flex;
  padding-top: 0;
  padding-left: 40px;
  padding-right: 40px;
  padding-bottom: 0;
  gap: 35px;
  max-width: 1400px;
  margin: 0 auto;
}

/* 左侧：热门城市 - 减小尺寸 */
.left-section {
  width: 25%;
  position: sticky;
  top: 80px;
  height: fit-content;
  background-color: white;
  border-radius: 15px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
  padding: 20px;
  transition: transform 0.3s ease;
}



.left-section h2 {
  font-size: 1.2rem;
  margin-bottom: 20px;
  color: #333;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.left-section h2 i {
  color: #FF6B6B;
}

.hot-cities-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.hot-cities-list li {
  display: flex;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.hot-cities-list li:last-child {
  border-bottom: none;
}

.city-rank {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: #f0f0f0;
  color: #777;
  font-size: 12px;
  font-weight: bold;
  margin-right: 12px;
}

.city-rank.top-three {
  background: linear-gradient(135deg, #FF6B6B 0%, #FF8E8E 100%);
  color: white;
  box-shadow: 0 2px 5px rgba(255, 107, 107, 0.3);
}

.city-name {
  flex: 1;
  font-size: 14px;
  color: #444;
}

.city-trend {
  color: #aaa;
  font-size: 12px;
}

.city-trend .fa-arrow-up {
  color: #FF6B6B;
}

.city-trend .fa-arrow-down {
  color: #4ECDC4;
}

/* 右侧：主题旅行 */
.right-section {
  width: 75%;
}

.right-section h2 {
  font-size: 1.4rem;
  margin-bottom: 25px;
  color: #333;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 10px;
}

.right-section h2 i {
  color: #17a2b8;
}

.theme-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(230px, 1fr));
  gap: 20px;
}

.theme-card {
  background-color: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
  transition: all 0.4s ease;
}

.theme-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 12px 20px rgba(0, 0, 0, 0.12);
}

.theme-image {
  position: relative;
  height: 160px;
  overflow: hidden;
}

.theme-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s ease;
}

.theme-card:hover .theme-image img {
  transform: scale(1.05);
}

.theme-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  background: linear-gradient(to top, rgba(0,0,0,0.7) 0%, rgba(0,0,0,0) 100%);
  padding: 20px;
  color: white;
  opacity: 0;
  transform: translateY(20px);
  transition: all 0.3s ease;
}

.theme-card:hover .theme-overlay {
  opacity: 1;
  transform: translateY(0);
}

.theme-content {
  padding: 15px;
}

.theme-content h3 {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #333;
}

.theme-content p {
  margin: 0;
  font-size: 13px;
  color: #777;
  line-height: 1.5;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .content-layout {
    padding: 30px;
    gap: 25px;
  }

  .left-section {
    width: 30%;
  }

  .right-section {
    width: 70%;
  }
}

@media (max-width: 768px) {
  .content-layout {
    flex-direction: column;
    padding: 20px;
  }

  .left-section,
  .right-section {
    width: 100%;
  }

  .left-section {
    position: static;
    margin-bottom: 20px;
  }

  .pin-wall-container {
    height: 20vh;
  }

  .pin {
    width: 220px;
    height: 24vh;
  }

  .search-box {
    width: 90%;
  }

  .theme-grid {
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  }
}

@media (max-width: 480px) {
  .theme-grid {
    grid-template-columns: 1fr;
  }

  .pin {
    width: 180px;
    height: 20vh;
  }

  .search-box button {
    padding: 10px 15px;
  }

  .content-layout {
    padding: 15px;
  }
}
.pin-overlay i {
  margin-right: 5px;
}

.text-red {
  color: red;
}

.text-gray {
  color: gray;
}
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal {
  background: white;
  padding: 20px;
  border-radius: 10px;
  width: 300px;
}

h3 {
  margin-bottom: 10px;
}

ul {
  list-style: none;
  padding: 0;
}

li {
  padding: 8px;
  border: 1px solid #ccc;
  margin: 5px 0;
  cursor: pointer;
}

li.active {
  background: #007bff;
  color: white;
}

.modal-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

button {
  padding: 5px 10px;
  border: none;
  cursor: pointer;
}

button:disabled {
  background: #ccc;
}

.folder-list {
  list-style: none;
  padding: 0;
  margin: 0;
  max-height: 300px;
  overflow-y: auto;
}

.folder-list li {
  padding: 10px;
  border-radius: 8px;
  cursor: pointer;
  margin-bottom: 8px;
  background-color: #f5f5f5;
  transition: 0.3s;
}

.folder-list li:hover {
  background-color: #e0e0e0;
}

.folder-list li.active {
  background-color: #409EFF;
  color: white;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>